<template>
  <div v-loading="!form">
    <el-form
      v-if="form"
      ref="surveyForm"
      :model="form"
      :rules="rules"
      label-width="20%"
      label-suffix="："
      class="form-fixed"
      @submit.native.prevent
    >
      <el-tabs v-model="activeName">
        <el-tab-pane
          label="基本信息"
          name="base"
        >
          <el-form-item
            label="变电站"
            prop="substation_id"
            class="form-item--medium"
          >
            <el-cascader
              v-model="form.substation_id"
              placeholder="请选择变电站"
              :options="options.substations"
              :props="{value:'id', label:'name',emitPath: false}"
              :show-all-levels="false"
              clearable
            >
              <template slot-scope="{ node, data }">
                <span>{{ data.name }}</span>
                <span v-if="node.isLeaf"> ({{ data.status.label }}) </span>
                <span v-else> ({{ data.children.length }}) </span>
              </template>
            </el-cascader>
          </el-form-item>
          <el-form-item
            label="检查项目"
            prop="categorys"
          >
            <el-cascader
              v-model="form.cid"
              placeholder="可按名称检索"
              :options="categorys"
              :props="{value:'id', label:'name', checkStrictly: true, emitPath: false}"
              filterable
              clearable
            />
          </el-form-item>
          <el-form-item
            label="隐患位置"
            prop="position"
            inline-message
            class="form-item--medium"
          >
            <el-input
              v-model="form.position"
              type="textarea"
              :rows="2"
              placeholder="请输入隐患所在位置，例如：10kV高压室室外西北侧电缆沟（可增加具体定位描述，13号-80号盖板，或2号-4号防火墙）"
            />
          </el-form-item>
          <el-form-item
            label="隐患内容"
            prop="content"
            class="form-item--medium"
          >
            <el-input
              v-model="form.content"
              type="textarea"
              :rows="2"
              placeholder="请输入隐患内容，例如：#1、#2站用变压器低压侧至站用电屏的两条电缆同沟敷设"
            />
          </el-form-item>

          <el-form-item
            ref="formInput.medias"
            label="隐患影音资料"
            prop="medias"
          >
            <uploader
              v-model="form.medias"
              :ratio="1"
              :limit="10"
              column-width="130px"
              multiple
              type="media"
              channel="oss"
              :accept="accepts"
              :max-allow-file-size="10*1024*1024"
              tips="隐患照片为必传项，资料缺失可上传文字说明照片，有需要可增加视频。"
            />
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane
          label="扩展信息"
          name="extend"
        >
          <el-form-item
            label="隐患等级"
            prop="danger_level_id"
            class="form-item--medium"
          >
            <el-select
              v-model="form.danger_level_id"
              clearable
              placeholder="请选择隐患等级"
            >
              <el-option
                v-for="(item,index) in options.dangerLevels"
                :key="index"
                :label="item.name"
                :value="item.id"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="是否治理完成"
            prop="solved"
            class="form-item--medium"
          >
            <el-switch
              v-model="form.solved"
              active-color="#13ce66"
              :active-value="1"
              :inactive-value="0"
              inactive-color="#ff4949"
            />
          </el-form-item>
          <el-form-item
            label="治理措施"
            prop="solution"
            class="form-item--medium"
          >
            <el-input
              v-model="form.solution"
              type="textarea"
              :rows="2"
              placeholder="输入治理的具体措施办法"
            />
          </el-form-item>
          <el-form-item
            label="治理前防范措施"
            prop="pretreatment"
            class="form-item--medium"
          >
            <el-input
              v-model="form.pretreatment"
              type="textarea"
              :rows="2"
              placeholder="输入治理前的防范措施"
            />
          </el-form-item>

          <el-form-item
            label="治理责任单位"
            prop="department_id"
            class="form-item--medium"
          >
            <el-select
              v-model="form.department_id"
              clearable
              placeholder="可选择治理责任单位"
            >
              <el-option
                v-for="(item,index) in options.departments"
                :key="index"
                :label="item.name"
                :value="item.id"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="治理负责人"
            prop="director"
            class="form-item--medium"
          >
            <el-input
              v-model="form.director"
              maxlength="50"
            />
          </el-form-item>
          <el-form-item
            label="计划治理时间"
            prop="plan_time"
          >
            <el-date-picker
              v-model="form.plan_time"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择计划治理时间"
              @change="onChangeDate"
            />
          </el-form-item>
          <el-form-item
            label="治理完成时间"
            prop="completed_at"
          >
            <el-date-picker
              v-model="form.completed_at"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择治理完成时间"
              @change="onChangeDate"
            />
          </el-form-item>
          <el-form-item
            ref="formInput.attachs"
            label="治理完成影音资料"
            prop="attachs"
          >
            <uploader
              v-model="form.attachs"
              :ratio="1"
              :limit="10"
              column-width="130px"
              multiple
              type="media"
              channel="oss"
              :accept="accepts"
              :max-allow-file-size="10*1024*1024"
              tips="治理完成后请上传至少1张治理结果的清晰图片。"
            />
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
      <fixed-box>
        <el-form-item>
          <div>
            <el-button
              type="primary"
              @click="onSubmit"
            >提交保存</el-button>
          </div>
          <div>
            <slot name="steps" />
            <el-button @click="goBack">返回</el-button>
          </div>
        </el-form-item>
      </fixed-box>
    </el-form>
  </div>
</template>

<script>
import Uploader from '@/components/Uploader/index'
import FixedBox from '@/layout/components/FixedBox'
export default {
  name: 'GoodsBaseForm',
  components: {
    Uploader,
    FixedBox
  },
  inject: ['goBack'],
  props: {
    value: {
      type: [Number, String],
      default: 0
    }
  },
  data() {
    var validateMedias = (rule, value, callback) => {
      console.log('validateMedias', value)
      var imageMedia = value.find(item => {
        return item.type === 'image'
      })
      if (!imageMedia) {
        callback(new Error('请上传至少1张隐患内容的清晰图片'))
      } else {
        callback()
      }
    }
    var validateAttachs = (rule, value, callback) => {
      if (this.form.solved) {
        if (value.length > 0) {
          var imageMedia = value.find(item => {
            return item.type === 'image'
          })
          if (!imageMedia) {
            callback(new Error('请上传至少1张治理完成影音资料的清晰图片'))
          } else {
            callback()
          }
        } else {
          callback(new Error('请上传至少1张治理完成影音资料的清晰图片!'))
        }
      } else {
        callback()
      }
    }
    return {
      accepts: ['image/jpeg', 'image/gif', 'image/png', 'image/bmp', 'video/mp4', 'audio/mpeg'],
      activeName: 'base',
      cascaderProps: {
        value: 'id',
        label: 'name',
        emitPath: true
      },
      rules: {
        substation_id: [{ required: true, message: '请选择变电站', trigger: 'change' }],
        medias: [
          {
            type: 'array',
            required: true,
            message: '请上传隐患内容的影音资料',
            trigger: 'change'
          },
          {
            validator: validateMedias,
            trigger: 'change'
          }
        ],
        attachs: [{ validator: validateAttachs, trigger: 'blur' }]
      },
      form: null,
      options: null,
      safeAttributes: []
    }
  },
  computed: {
    // voltages() {
    //   var substationVoltages = this.options.substations.map(item => {
    //     return {
    //       id: item.voltage_id,
    //       name: item.voltage
    //     }
    //   })
    //   const removeDuplicateObj = arr => {
    //     var obj = {}
    //     arr = arr.reduce((newArr, next) => {
    //       if (!obj[next.id]) {
    //         obj[next.id] = true
    //         newArr.push(next)
    //       }
    //       return newArr
    //     }, [])
    //     return arr
    //   }
    //   return removeDuplicateObj(substationVoltages)
    // },
    // substations() {
    //   return this.options.substations.filter(item => {
    //     return !this.form.voltage_id || item.voltage_id === this.form.voltage_id
    //   })
    // },
    stages() {
      return this.options.stages.map(item => {
        var idString = item.id
        console.log(item)
        if (item.disabled) {
          var index = this.form.stages.indexOf(idString)
          if (index !== -1) {
            this.form.stages.splice(index, 1)
          }
        }
        return item
      })
    },
    categorys() {
      return this.options.categorys.map(item => {
        return item
      })
    },
    visitmodeRooms() {
      var roomIds = this.rooms.map(item => {
        return item.id
      })
      var mins = roomIds
      var categorys = []
      if (this.form.categorys && this.form.categorys.length > 0) {
        for (var i = 0; i < this.form.categorys.length; i++) {
          var visitMode = this.categorys.find(mode => {
            return mode.id === this.form.categorys[i]
          })
          categorys.push(visitMode)
        }
      }
      for (i = 0; i < categorys.length; i++) {
        const { rooms } = categorys[i]
        mins = this.$utils.arrayDiff(mins, rooms)
      }
      return this.rooms.map(item => {
        var disabled = item.disabled
        if (!disabled && mins.indexOf(item.id) === -1) {
          disabled = true
        }
        if (disabled && this.form.room_id !== '' && this.form.room_id === item.id) {
          this.form.room_id = ''
        }
        return { ...item, disabled: disabled }
      })
    },
    dateStart() {
      const now = new Date()
      now.setDate(now.getDate() + 2)
      const date = this.$moment(now).format('yyyy-mm-dd')
      console.log(date)
      return date
    },
    dateEnd() {
      const now = new Date()
      now.setDate(now.getDate() + 60)
      const date = this.$moment(now).format('yyyy-mm-dd')
      console.log(date)
      return date
    },
    currentDate() {
      const now = new Date()
      now.setDate(now.getDate() + 2)
      return this.$moment(now).format('yyyy-mm-dd')
    }
  },
  mounted() {
    this.onLoad()
  },
  methods: {
    disabledDate(date) {
      var weekend = !(date.getDay() % 6)
      return weekend || this.$moment().isAfter(date, 'day') // 禁止选择今天以后的时间
    },
    onLoad() {
      this.$http.work.formConfig(this.value).then(res => {
        console.log('onLoadConfig', res.data)
        this.onMountData(res.data)
      })
    },
    onMountData(data) {
      const { form, options, safeAttributes } = data
      this.form = { ...form }
      console.log('medias::', this.form.medias)
      this.options = options
      this.safeAttributes = safeAttributes
    },
    onChangeDate(date) {
      console.log(date)
      this.form.date = date
      this.onCheckOnlineStage(date, this.id)
    },
    onCheckOnlineStage(date, bookId) {
      this.$http.book.checkBookStage(date, bookId).then(res => {
        const stages = res.data
        this.options.stages = stages
        console.log(this.options.stages)
      })
    },
    onSubmit() {
      this.$refs.surveyForm.validate((valid, obj) => {
        if (valid) {
          this.submit()
        } else {
          let firstErrorElname = ''
          for (const i in obj) {
            firstErrorElname = `formInput.${i}`
            break
          }
          if (firstErrorElname === 'formInput.attachs') {
            this.activeName = 'extend'
          } else {
            this.activeName = 'base'
          }
          var dom = this.$refs[firstErrorElname]
          console.log(dom, this.$refs)
          if (dom) {
            dom.$refs.input && dom.$refs.input.focus()
            dom.$el.scrollIntoView({
              // 滚动到指定节点
              block: 'center', // 值有start,center,end，nearest，当前显示在视图区域中间
              behavior: 'smooth' // 值有auto、instant,smooth，缓动动画（当前是慢速的）
            })
          }
          console.log('error submit!!', this.form)
          return false
        }
      })
    },
    submit() {
      this.$http.work.update(this.form, this.value).then(res => {
        if (res.data) {
          this.$emit('submit', res.data)
        }
      })
    }
  }
}
</script>
